import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * @author liliang
 * @description:
 * @date 2018/3/3.
 */
public class AlgoVisualizer {

    private Circle[] circles;
    private AlgoFrame frame;
    private boolean isAnmiated = true;

    /**
     * 初始化数据
     *
     * @param sceneWidth
     * @param sceneHeight
     * @param n
     */
    public AlgoVisualizer(int sceneWidth, int sceneHeight, int n) {

        circles = new Circle[n];
        int r = 50;
        for (int i = 0; i < n; i++) {
            int x = (int) (Math.random() * (sceneWidth - 2 * r)) + r;
            int y = (int) (Math.random() * (sceneHeight - 2 * r)) + r;
            int vx = (int) (Math.random() * 11) - 5;
            int vy = (int) (Math.random() * 11) - 5;
            circles[i] = new Circle(x, y, r, vx, vy);
        }

        // 初始化视图
        EventQueue.invokeLater(() -> {
            frame = new AlgoFrame("Welcome", sceneWidth, sceneHeight);
            frame.addKeyListener(new AlgoKeyListener());

            new Thread(() -> {
                run();
            }).start();
        });
    }

    /**
     * 动画逻辑
     */

    private void run() {
        while (true) {
            // 绘制数据
            frame.render(circles);
            AlgoVisHelper.pause(20);
            if (isAnmiated) {
                // 更新数据
                for (Circle circle : circles) {
                    circle.move(0, 0, frame.getCanvasWidth(), frame.getCanvasHeight());
                }
            }
        }
    }

    /**
     * 键盘事件
     */
    private class AlgoKeyListener extends KeyAdapter {

        @Override
        public void keyReleased(KeyEvent e) {
            // 空格
            if (e.getKeyChar() == KeyEvent.VK_SPACE) {
                isAnmiated = !isAnmiated;
            }
        }
    }

    public static void main(String[] args) {

        int sceneWidth = 800;
        int sceneHeight = 800;
        int N = 10;
        new AlgoVisualizer(sceneWidth,sceneHeight,N);
    }
}
